package com.xinlong.shop.api.promotion;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinlong.shop.core.goods.entity.Goods;
import com.xinlong.shop.core.goods.entity.GoodsTypeEnum;
import com.xinlong.shop.core.goods.service.IGoodsService;
import com.xinlong.shop.core.member.service.IMemberService;
import com.xinlong.shop.core.promotion.entity.DetailStatusEnum;
import com.xinlong.shop.core.promotion.entity.PutSaleOrder;
import com.xinlong.shop.core.promotion.entity.RushPurchaseDetail;
import com.xinlong.shop.core.promotion.entity.RushPurchaseDetailQueryParam;
import com.xinlong.shop.core.promotion.service.IPutSaleOrderService;
import com.xinlong.shop.core.promotion.service.IRushPurchaseDetailService;
import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.framework.core.entity.Member;
import com.xinlong.shop.framework.service.ISysSettingService;
import com.xinlong.shop.framework.util.StringUtil;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 抢购活动明细表 前端控制器
 * </p>
 *
 * @author Sylow
 * @since 2023-02-17
 */
@RestController
@RequestMapping("/promotion/rush-purchase/detail")
public class RushPurchaseDetailController {

    private final IRushPurchaseDetailService rushPurchaseDetailService;
    private final IGoodsService goodsService;
    private final IMemberService memberService;
    private final ISysSettingService sysSettingService;
    private final IPutSaleOrderService putSaleOrderService;

    public RushPurchaseDetailController(IRushPurchaseDetailService rushPurchaseDetailService, IGoodsService goodsService, IMemberService memberService, ISysSettingService sysSettingService, IPutSaleOrderService putSaleOrderService) {
        this.rushPurchaseDetailService = rushPurchaseDetailService;
        this.goodsService = goodsService;
        this.memberService = memberService;
        this.sysSettingService = sysSettingService;
        this.putSaleOrderService = putSaleOrderService;
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public R page(Integer current, Integer size, RushPurchaseDetailQueryParam rushPurchaseDetailQueryParam){
        IPage<RushPurchaseDetail> page = new Page<>(current, size);
        rushPurchaseDetailQueryParam.setFilterStatus(DetailStatusEnum.CANCEL.getCode());
        page = this.rushPurchaseDetailService.findPageByParam(page, rushPurchaseDetailQueryParam);
        return R.success("操作成功", page);
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public R save(@Valid @RequestBody RushPurchaseDetail rushPurchaseDetail ){
        this.rushPurchaseDetailService.save(rushPurchaseDetail);
        return R.success("操作成功");
    }

    @RequestMapping(value = "batch-save", method = RequestMethod.POST)
    public R batchSave(@Valid @RequestBody List<RushPurchaseDetail> rushPurchaseDetails ){

        Long time = DateUtil.currentSeconds();
        for(RushPurchaseDetail pd : rushPurchaseDetails) {
            pd.setCreateTime(time);
            pd.setOrderSn("P" + pd.getActivityId() + StringUtil.random(10000) + pd.getGoodsId());
        }
        this.rushPurchaseDetailService.saveBatch(rushPurchaseDetails);
        return R.success("操作成功");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public R update(@Valid @RequestBody RushPurchaseDetail rushPurchaseDetail, @PathVariable("id") Integer id){
        this.rushPurchaseDetailService.update(rushPurchaseDetail, id);
        return R.success("操作成功",rushPurchaseDetail);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public R delete(@PathVariable("id") Integer id) {
        this.rushPurchaseDetailService.delete(id);
        return R.success("删除成功");
    }

    @RequestMapping(value = "/vip/{id}/{is_vip}", method = RequestMethod.PUT)
    public R updateVip(@PathVariable("id") Integer id, @PathVariable("is_vip") Integer isVip){
        //this.rushPurchaseDetailService.update(rushPurchaseDetail, id);
        this.rushPurchaseDetailService.updateVip(id, isVip);
        return R.success();
    }

    /**
     * 临时批量上架
     * @param memberId
     * @param activityId
     * @return
     */
    @RequestMapping(value = "/batch-put-sale", method = RequestMethod.GET)
    public R batchPutSale(Integer memberId, String activityId) {
        List<RushPurchaseDetail> list = this.rushPurchaseDetailService.findBuyerOrder(memberId, activityId);
        for(RushPurchaseDetail pd : list) {
            //rushPurchaseDetail.setStatus(DetailStatusEnum.SALE.getCode());

            // 获取系统配置
            Map<String, Object> setting = sysSettingService.getSetting();
            Double priceMarkup = (Double) setting.get("priceMarkup"); // 费用增幅百分比
            Double putSalePrice = (Double) setting.get("putSalePrice"); // 服务费百分比

            // 计算价格和服务费
            BigDecimal sellPrice = getPrice(pd.getPrice(), priceMarkup);
            // 服务费是购买的价格来计算
            BigDecimal priceService = getServicePrice(pd.getPrice(), putSalePrice);

            // 设置费用精度
            sellPrice = sellPrice.setScale(0, BigDecimal.ROUND_HALF_UP);
            priceService = priceService.setScale(0, BigDecimal.ROUND_HALF_UP);


            PutSaleOrder order = new PutSaleOrder();
            order.setOrderSn(pd.getOrderSn());
            order.setOriginalPrice(pd.getPrice());
            order.setNewPrice(sellPrice);
            order.setServicePrice(priceService);
            order.setRushPurchaseDetailId(pd.getId());
            order.setRushPurchaseId(pd.getRushPurchaseId());
            order.setMemberId(pd.getBuyerId());

            boolean result = this.putSaleOrderService.savePutSaleOrder(order);
            if (!result) {
                return R.error("操作失败");
            }
        }
        return R.success(list.size());
    }

    /**
     * 获取所有商品，暂时给商品选择使用，后期作废 前端换成分页的
     * @return
     */
    @RequestMapping(value = "/goods-list", method = RequestMethod.GET)
    public R goodsList(Integer rushPurchaseId, String goodsName){
        if(rushPurchaseId == null) {
            return R.error("抢购id必填");
        }
        List<RushPurchaseDetail> details = this.rushPurchaseDetailService.listByRushPurchaseId(rushPurchaseId);

        List<Integer> ids = new ArrayList<>();
        for (RushPurchaseDetail rushPurchaseDetail : details) {
            ids.add(rushPurchaseDetail.getGoodsId());
        }

        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if(!ids.isEmpty()){
            queryWrapper.notIn("id", ids);
        }

        if (StrUtil.isNotBlank(goodsName)) {
            queryWrapper.like("goods_name", goodsName);
        }

        queryWrapper.eq("goods_type", GoodsTypeEnum.RUSH_PURCHASE.getCode());

        List<Goods> list = this.goodsService.list(queryWrapper);
        return R.success("操作成功", list);
    }

    /**
     * 获取所有会员，暂时给会员选择使用，后期作废 前端换成分页的
     * @return
     */
    @RequestMapping(value = "/member-list", method = RequestMethod.GET)
    public R memberList(String memberName){
        if (memberName == null) {
            memberName = "";
        }
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("member_name", memberName)
                .or()
                .like("mobile", memberName)
                .or()
                .like("nickname", memberName)
                .or()
                .like("member_no", memberName);
        List<Member> list = this.memberService.list(queryWrapper);
        return R.success("操作成功", list);
    }


    /**
     * 以下代码是临时给线上批量上架用的  用完后可删除
     */

    /**
     * 获取新上架价格
     * @param price 原价
     * @param priceMarkup 涨幅
     * @return
     */
    private BigDecimal getPrice(BigDecimal price, Double priceMarkup){

        // 配置中是整数 需要除以100
        Double divisor = 100D;
        priceMarkup = NumberUtil.div(priceMarkup, divisor, 3);

        // 新价格= 原价+原价*增幅百分比
        price = NumberUtil.add(price,NumberUtil.mul(price, priceMarkup));


        return price;
    }

    /**
     * 获取服务费金额
     * @param price 商品价格
     * @param putSalePrice 服务费百分比
     * @return
     */
    private BigDecimal getServicePrice(BigDecimal price, Double putSalePrice){

        // 配置中是整数 需要除以100
        Double divisor = 100D;
        putSalePrice = NumberUtil.div(putSalePrice, divisor, 3);

        // 服务费=新价格*百分比
        BigDecimal servicePrice = NumberUtil.mul(price, putSalePrice);

        return servicePrice;
    }

}
